package cn.ixiaoxin.deepchat.service.impl;

import cn.ixiaoxin.deepchat.DTO.ChatHistoryDTO;
import cn.ixiaoxin.deepchat.DTO.MessageDTO;
import cn.ixiaoxin.deepchat.entity.Message;
import cn.ixiaoxin.deepchat.mapper.MessageMapper;
import cn.ixiaoxin.deepchat.service.MessageService;
import cn.ixiaoxin.deepchat.util.Result;
import cn.ixiaoxin.deepchat.websocket.WebSocketServer;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Service
public class MessageServiceImpl implements MessageService {

    private final MessageMapper messageMapper;

    private final WebSocketServer webSocketServer;

    @Override
    public Result<?> sendMessage(MessageDTO messageDTO) {
        Message message = new Message();
        message.setFromId(messageDTO.getFromId());
        message.setToId(messageDTO.getToId());
        message.setType(messageDTO.getMessageType());
        message.setContent(messageDTO.getContent());
        message.setCreateTime(LocalDateTime.now());
        message.setFileName(messageDTO.getFileName());
        message.setFileSize(messageDTO.getFileSize());
        messageMapper.insert(message);

        // 构造返回结果，包含消息ID
        JSONObject result = new JSONObject();
        result.put("messageId", message.getId());
        result.put("content", message.getContent());
        result.put("createTime", message.getCreateTime());

        // 构造符合前端预期的WebSocket消息格式
        JSONObject wsMessage = new JSONObject();
        wsMessage.put("type", "single");
        wsMessage.put("fromId", messageDTO.getFromId());
        wsMessage.put("toId", messageDTO.getToId());
        wsMessage.put("messageType", messageDTO.getMessageType());
        wsMessage.put("content", messageDTO.getContent());

        webSocketServer.handleSingleMessage(String.valueOf(message.getFromId()), wsMessage);
        return Result.success(result);
    }

    @Override
    public Result<?> getChatHistory(ChatHistoryDTO chatHistoryDTO) {
        Page<Message> page = new Page<>(chatHistoryDTO.getPageNum(), chatHistoryDTO.getPageSize());
        QueryWrapper<Message> query = new QueryWrapper<Message>()
                .and(wrapper -> wrapper
                        .eq("from_id", chatHistoryDTO.getFormId())
                        .eq("to_id", chatHistoryDTO.getToId())
                        .or()
                        .eq("from_id", chatHistoryDTO.getToId())
                        .eq("to_id", chatHistoryDTO.getFormId()))
                .orderByDesc("create_time");
        List<Message> messages = messageMapper.selectPage(page, query).getRecords();
        return Result.success(messages);
    }
}
